package cn.community.system.shiro;

import cn.community.system.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;


public class AjaxFormAuthenticationFilter extends FormAuthenticationFilter {

    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        //使用response对象输出数据(json字符串)
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().print(JsonResult.success());
        return false; //不放行
    }

    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        //异常信息打印出来
        e.printStackTrace();
        JsonResult json = null;
        if(e instanceof UnknownAccountException){  // 用户名错误
            json = JsonResult.error(JsonResult.CODE_ERROR_INCORRECT,JsonResult.MSG_INCORRECT,null);
        }else if(e instanceof IncorrectCredentialsException){  // 密码错误
            json = JsonResult.error(JsonResult.CODE_ERROR_INCORRECT,JsonResult.MSG_INCORRECT,null);
        }
        //使用response对象输出数据(json字符串)
        response.setContentType("application/json;charset=utf-8");
        try {
            response.getWriter().print(JSON.toJSONString(json));
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return false; //不放行
    }
}
